/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.model.clazz;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.Caffein;
import com.koylu.caffein.Cascade;
import com.koylu.caffein.exception.ClazzConfigException;
import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.id.CompositeId;
import com.koylu.caffein.model.clazz.validation.ValidateFor;
import com.koylu.caffein.model.clazz.validation.Validation;
import com.koylu.caffein.model.container.CollectionContainer;
import com.koylu.caffein.model.container.Container;
import com.koylu.caffein.model.handler.OneToManyContainerHandler;
import com.koylu.caffein.query.GenericQuery;
import com.koylu.caffein.query.Query;
import com.koylu.caffein.query.filter.Filter;
import com.koylu.caffein.query.join.Join;

@SuppressWarnings("unchecked")
public class OneToMany extends Relation {

	private String name;
	private String clazz;
	private Node parent;
	private Collection<Key> children;
	private Class returnType;
	private Class<?> proxyClass;
	private List<Validation> validations;
	private String cascade = Cascade.NOACTION.name();

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}
	
	public Clazz getForeignClazz(CaffeinConfig caffeinConfig) throws Exception {
		Clazz clazzz = caffeinConfig.getClazz(clazz);
		if(clazzz == null){
			throw new ClazzConfigException("clazz not found:"+clazz, this);
		}
		return clazzz;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}

	public String getCascade() {
		return cascade;
	}

	public void setCascade(String cascade) {
		this.cascade = cascade.toUpperCase(Locale.ENGLISH);
	}

	public void addChild(Node child) throws Exception{
		if(child instanceof ForeignKey){
			throw new ClazzConfigException("foreign-key not allowed for oneToMany", this);
		}
		if (children == null) {
			children = new ArrayList<Key>();
		}
		child.setParent(this);
		children.add((Key) child);
	}

	public Collection<Key> getChildren() {
		return children;
	}

	Boolean isSimple;
	public Object toObject(CaffeinConfig caffeinConfig, Object object, ResultSet resultSet) throws Exception {
		if (isSimple == null) {
			isSimple = !(((Clazz) getParent()).getId() instanceof CompositeId);
		}
		if (returnType == null) {
			returnType = collectionTypes.get(getRealClass(caffeinConfig).getName());
		}
		if (isSimple) {
			return toSimpleObject(caffeinConfig, resultSet);
		}
		return toCompositeObject(caffeinConfig, resultSet);
	}

	Key key = null;
	public Object toSimpleObject(CaffeinConfig caffeinConfig, ResultSet resultSet) throws Exception {
		if (key == null) {
			key = getChildren().iterator().next();
		}
		Query query = new GenericQuery(caffeinConfig, ((Clazz) getParent()), "local_table");
		query.addJoin(Join.inner("foreign_table", getName()), true);
		query.addFilter(Filter.eq("local_table", key.getRealNode(caffeinConfig).getPath(caffeinConfig), key.getConverter(caffeinConfig).columnToField(resultSet, key.getRealNode(caffeinConfig).getColumnAlias())));
		Object object = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) object).setHandler(new OneToManyContainerHandler(returnType, query));
		return object;
	}

	public Object toCompositeObject(CaffeinConfig caffeinConfig, ResultSet resultSet) throws Exception {
		Query query = new GenericQuery(caffeinConfig, ((Clazz) getParent()), "local_table");
		query.addJoin(Join.inner("foreign_table", getName()), true);
		for (Key key : getChildren()) {
			query.addFilter(Filter.eq("local_table", key.getRealNode(caffeinConfig).getPath(caffeinConfig), key.getConverter(caffeinConfig).columnToField(resultSet, key.getRealNode(caffeinConfig).getColumnAlias())));
		}
		Object object = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) object).setHandler(new OneToManyContainerHandler(returnType, query));
		return object;
	}
	
	public Object toEmptyObject(CaffeinConfig caffeinConfig, Clazz clazz) throws Exception {
		if (returnType == null) {
			returnType = collectionTypes.get(getRealClass(caffeinConfig).getName());
		}
		return returnType.newInstance();
	}
	
	public Class<?> getProxyClass(CaffeinConfig caffeinConfig) throws Exception {
		if(proxyClass == null){
			ProxyFactory proxyFactory = new ProxyFactory();
			proxyFactory.setSuperclass(returnType);
			proxyFactory.setInterfaces(CollectionContainer.interfaces);
			proxyFactory.setFilter(Container.methodFilter);
			proxyClass = proxyFactory.createClass();
		}
		return proxyClass;
	}

	private Class<?> realClass;
	private Class<?> getRealClass(CaffeinConfig caffeinConfig) throws Exception {
		if(realClass == null){
			if(virtualClass == null){
				realClass = CaffeinConfig.getFieldType(((Clazz)getParent()).getRealClass(caffeinConfig), name);
			}else{
				realClass = virtualClass;
			}			
		}
		return realClass;
	}

	private Class<?> virtualClass;
	public Class<?> toVirtualClass(CaffeinConfig caffeinConfig) throws Exception {
		if(virtualClass == null){
			virtualClass = List.class;
		}
		return virtualClass;
	}

	public Object copy(CaffeinConfig caffeinConfig, Object object) throws Exception {
		CollectionContainer collectionContainer = (CollectionContainer) object;
		Object newObject = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) newObject).setHandler(new OneToManyContainerHandler(returnType, collectionContainer.getQuery()));
		return newObject;
	}
	
	public List<Validation> getValidations() {
		return validations;
	}

	public void setValidations(List<Validation> validations) {
		this.validations = validations;
	}
	
	public void validate(CaffeinConfig caffeinConfig, Clazz clazz, Object object, ValidateFor validateFor) throws Exception {
		if (validations != null) {
			for (Validation validation : validations) {
				validation.validate(caffeinConfig, clazz, this, object, validateFor);
			}
		}
	}
	
	public void save(CaffeinConfig caffeinConfig, Connection connection, Object object) throws Exception {}
	
	public void update(CaffeinConfig caffeinConfig, Connection connection, Object object) throws Exception {}
	
	public void delete(CaffeinConfig caffeinConfig, Clazz clazz, Connection connection, Object object) throws Exception {
		if (Cascade.DELETE.equals(Cascade.valueOf(cascade))) {
			Caffein caffein = caffeinConfig.getCaffein();
			Clazz foreignClazz = getForeignClazz(caffeinConfig);
			for (Object foreignObject : (Collection<?>) PropertyUtils.getProperty(object, getName())) {
				try {
					caffein.delete(foreignClazz, connection, PropertyUtils.getProperty(foreignObject, foreignClazz.getId().getName()));	
				} catch (Exception e) {
					throw new RuntimeException("oneToMany delete error["+name+"]", e);
				}
			}
		}else if (Cascade.SETNULL.equals(Cascade.valueOf(cascade))) {
			Clazz foreignClazz = getForeignClazz(caffeinConfig);
			Field foreignField = foreignClazz.findField(ManyToOne.class, "clazz", clazz.getName());
			if (foreignField != null) {
				if( ((Collection<?>)PropertyUtils.getProperty(object, name)).size() > 0 ){
					PreparedStatement preparedStatement = caffeinConfig.getObjectToQuery().updateOneToMany(caffeinConfig, (ManyToOne)foreignField, connection, foreignClazz, object);
					try {
						preparedStatement.executeUpdate();						
					} catch (Exception e) {
						throw new RuntimeException("oneToMany update error["+name+"]", e);
					}finally{
						if(preparedStatement != null){
							try {
								preparedStatement.close();								
							} catch (Exception e) {}
						}
					}
				}
			}
		}		
	}
	
	public String getPath(CaffeinConfig caffeinConfig) throws Exception {
		return name;
	}

	public String toString() {
		return getClass().getName()+"["+name+"]";
	}
}